import { defineStore } from 'pinia'
import api from '@/http/index'
import useEnterpriseStore from './enterprise'
import { replacePlaceholder } from '@/common/utils/string'
import regexp from '@/common/utils/regexp'
import * as tree from '@/common/utils/tree'

const useMenuStore = defineStore('menu', {
  state: () => ({
    menuTree: [], // 菜单列表
    active: {}, // 当前激活的菜单
  }),
  actions: {
    async init() {
      if (this.menuTree.length) return this.menuTree
      const result = await api.auth.getPermMenus()
      const menuTree = (result.data || []).map((route) => {
        const path = this.handlePath(route.path)
        return {
          ...route,
          path,
          isSystem: !regexp.http.test(path) || !regexp.https.test(path),
        }
      })
      this.menuTree = menuTree
      return this.menuTree
    },
    setActive(menuId) {
      if (menuId === this.active?.menuId) return
      this.active = tree.findItem(this.menuTree, 'children', (item) => item.menuId === menuId)
    },
    handlePath(path = '') {
      path = replacePlaceholder(path.trim(), this.pathPlaceholderEnum)
      const origin = location.origin
      if (path.startsWith(origin)) {
        path = path.replace(origin, '')
      }
      return path
    },
  },
  getters: {
    pathPlaceholderEnum() {
      const enterpriseStore = useEnterpriseStore()
      return {
        ...window.domain_config,
        enterprise_id: enterpriseStore.enterpriseId,
      }
    },
  },
})
export default useMenuStore
